// popup.js - 显示事件
const eventsContainer = document.getElementById('events');
let eventCount = 0;

// 检查扩展上下文是否有效
function checkExtensionContext() {
  try {
    return !!(chrome.runtime && chrome.runtime.id);
  } catch (error) {
    console.log('扩展上下文无效:', error);
    return false;
  }
}

// 接收来自 content.js 的消息
chrome.runtime.onMessage.addListener((message) => {
  if (!checkExtensionContext()) {
    return;
  }
  
  if (message.type !== 'heartbeat') { // 忽略心跳消息
    addEvent(message);
  }
});

// 添加事件到界面
function addEvent(data) {
  const div = document.createElement('div');
  div.className = 'event';

  let content = `<span class="type">${data.type === 'click' ? '🖱 点击' : data.type === 'key' ? '⌨️ 按键' : '🔄 心跳'}</span> <span class="time">${data.time}</span>`;

  if (data.type === 'click') {
    content += `<pre>标签: ${data.tag}
ID: ${data.id}
Class: ${data.class}
文本: ${data.text}
${data.value}
XPath: ${data.xpath || '无'}
CSS选择器: ${data.cssSelector || '无'}</pre>`;
  } else if (data.type === 'key') {
    content += `<pre>键: "${data.key}" (${data.code})
修饰键: ${data.modifiers}
目标: ${data.target}
XPath: ${data.xpath || '无'}
CSS选择器: ${data.cssSelector || '无'}</pre>`;
  }

  div.innerHTML = content;
  eventsContainer.prepend(div);
  eventCount++;

  // 只保留最近 10 条
  while (eventsContainer.children.length > 10) {
    eventsContainer.lastChild.remove();
  }

  // 清除初始提示文本
  if (eventsContainer.textContent.includes('正在等待事件')) {
    eventsContainer.innerHTML = '';
    eventsContainer.prepend(div);
  }
}

// 安全地获取最后事件
function getLastEventSafely() {
  if (!checkExtensionContext()) {
    console.log('扩展上下文无效，无法获取事件');
    return;
  }

  try {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (chrome.runtime.lastError) {
        console.log('查询标签页失败:', chrome.runtime.lastError.message);
        return;
      }
      
      if (tabs && tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {action: 'getLastEvent'}, function(response) {
          if (chrome.runtime.lastError) {
            console.log('发送消息失败:', chrome.runtime.lastError.message);
            return;
          }
          
          if (response) {
            addEvent(response);
          }
        });
      }
    });
  } catch (error) {
    console.log('获取最后事件失败:', error.message);
  }
}

// 初始化
console.log('插件面板已打开');
setTimeout(getLastEventSafely, 500); 